package com.alex.service.Search_Plans;

import co.elastic.clients.elasticsearch._types.query_dsl.MultiMatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;

import java.util.Set;

import static com.alex.service.Search_Plans.SearchPlanUtils.enWordIgnore;
import static com.alex.utils.MyUtils.zsout;


/**
 * @Author: 张福垒
 * @Date: 2024/11/27 16:32
 * @Description:
 * @phone: 13864677931
 */
public class Ts_match_query {
    /**
     * 针对主题的 分词的检索方法 根据输入的单次或者汉字长度来判断需要命中X/Y 或者 X% 之多少的数字
     *
     * @param freeWord
     * @return
     */
    public static Query ts_match_query(String freeWord, boolean printLog) {

        int wordCount = freeWord.length();  //默认算中文检索词的字数
        String minimumMatch;
        /**
         * 首先判断中英文混合输入的情况 如果是中英文混合输入单独处理直接走
         */
        if (SearchPlanUtils.isContainChineseAndEnglish(freeWord)) {
            zsout("[TS][混合][CN][EN][" + wordCount + "]   " + freeWord, printLog);
            if (wordCount <= 10) {
                minimumMatch = "99%";
            } else {
                minimumMatch = "95%";
            }
            String finalFreeWord1 = freeWord;
            return MultiMatchQuery.of(i -> i.fields(
                    "title^10",
                    "cn_ti^10",

                    "key_word_list",
                    "ab",
                    "cn_ab"
            ).query(finalFreeWord1).minimumShouldMatch(minimumMatch))._toQuery();
        }
        Set<String> set = enWordIgnore();
        for (String oneWord : set) {
            if (freeWord.contains(" " + oneWord + " ")) {
                freeWord = freeWord.replaceAll(" " + oneWord + " ", " ");
                freeWord = freeWord.replaceAll(" +", " ").trim();
            }
        }
        if (!SearchPlanUtils.isContainChinese(freeWord)) {//不过不包含中文就算单词个数
            wordCount = freeWord.split("\\s+").length;
            zsout("[TS][分词][EN][" + wordCount + "]   " + freeWord, printLog);
        } else {
            zsout("[TS][分词][CN][" + wordCount + "]   " + freeWord, printLog);
        }

        switch (wordCount) {
            case 1:
                minimumMatch = "100%";
                break;
            case 2:
                minimumMatch = "100%";
                break;
            case 3:
                minimumMatch = "100%";
                break;
            case 4:
                minimumMatch = "100%";
                break;
            case 5:
                minimumMatch = "3";
                break;
            default:
                minimumMatch = "99%";
                break;
        }

        String finalFreeWord = freeWord;
        return MultiMatchQuery.of(i -> i.fields(
                "title^10",
                "cn_ti^10",
                "ab",
                "cn_ab",
                "key_word_list"
        ).query(finalFreeWord).minimumShouldMatch(minimumMatch))._toQuery();

    }
}
